<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Files extends CI_Controller {

    private $user_id;

    public function __construct() {
        parent::__construct();
        $this->lang->load('breadcrumb', 'estonian');
         if ($this->session->userdata('is_admin') == false) {
            $this->session->set_flashdata('error', 'Administraatori lehekülje kasutamiseks logige palun vastavate õigustega sisse.');
            redirect('login');
            die();
        }
        $this->user_id = $this->session->userdata('id');
        $this->load->model('Athlete_model', 'AthleteModel');
        $this->load->model('Team_model', 'TeamModel');
        $this->load->model('Fina_model', 'FinaModel');
        $this->load->model('Result_model', 'ResultModel');
        $this->load->model('Competition_model', 'CompetitionModel');
    }

    public function index() {
        redirect('admin');
    }

    private function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    private function generate_file_name($user_id) {
        return $user_id . '_' . strftime('%Y-%m-%d') . '_' . $this->generateRandomString() . '.xml';
    }

    public function upload_athletes() {
        $config['upload_path'] = './uploads/athletes';
        $config['allowed_types'] = 'xml';
        $config['max_size'] = 0;
        $config['file_name'] = $this->generate_file_name($this->user_id);
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('athletes')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->template('admin/home', $error);
        } else {
            $upload_data = $this->upload->data();
            $full_path = $upload_data['full_path'];
            $data['full_path'] = $full_path;
            $data['results'] = $this->AthleteModel->athletes_from_xml_path($full_path);

            $this->load->template('admin/found_athletes', $data);
        }
    }

    public function add_athletes() {
        $full_path = $this->input->post('full_path');
        $athletes = $this->AthleteModel->athletes_from_xml_path($full_path);
        $this->AthleteModel->insert_athletes_to_db($athletes);

        redirect('admin');
    }

    public function upload_teams() {
        $config['upload_path'] = './uploads/teams';
        $config['allowed_types'] = 'xml';
        $config['max_size'] = 0;
        $config['file_name'] = $this->generate_file_name($this->user_id);
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('teams')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->template('admin/home', $error);
        } else {
            $upload_data = $this->upload->data();
            $full_path = $upload_data['full_path'];
            $data['full_path'] = $full_path;
            $teams = $this->TeamModel->teams_from_xml_path($full_path);

            $teams_old = array();
            $teams_new = array();
            foreach ($teams as &$team) {
                if ($this->TeamModel->team_exists($team->getFullName(), $team->getShortName(), $team->getAbbr())) {
                    $teams_old[] = $team;
                } else {
                    $teams_new[] = $team;
                }
            }

            $data['teams_old'] = $teams_old;
            $data['teams_new'] = $teams_new;

            $this->load->template('admin/found_teams', $data);
        }
    }

    public function add_teams() {
        $full_path = $this->input->post('full_path');
        $teams = $this->TeamModel->teams_from_xml_path($full_path);
        $this->TeamModel->insert_teams_to_db($teams);

        redirect('admin');
    }

    public function upload_results() {
        $competition_id = $this->input->post('competition_id');
        $config['upload_path'] = './uploads/results';
        $config['allowed_types'] = 'xml';
        $config['max_size'] = 0;
        $config['file_name'] = $this->generate_file_name($this->user_id);
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('results')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->template('admin/home', $error);
        } else {
            $upload_data = $this->upload->data();
            $full_path = $upload_data['full_path'];
            $data['full_path'] = $full_path;
            $data = $this->ResultModel->results_events_from_xml_path($full_path, $competition_id);
            $competition = Competition::fromID($competition_id);
            $start = strtotime($competition->getStartDate());
            $end = strtotime($competition->getEndDate());
            $days = ($end - $start) / 86400;
            $data['start_date'] = $competition->getStartDate();
            $data['days'] = $days;
            $data['num_events'] = count($data['events']);
            $data['competition_id'] = $competition_id;
            $data['full_path'] = $full_path;

            $this->load->template('admin/found_results1', $data);
        }
    }

    public function add_results() {
        $events = array();
        $full_path = $this->input->post('full_path');
        $competition_id = $this->input->post('competition_id');
        $data = $this->ResultModel->results_events_from_xml_path($full_path, $competition_id);

        $competition = Competition::fromID($competition_id);
        $start = strtotime($competition->getStartDate());
        $end = strtotime($competition->getEndDate());
        $days = ($end - $start);

        if ($days != 0) {
            $events_found = explode('</li>', $this->input->post('events'));
            foreach ($events_found as $row) {
                $date_match = array();
                $date = preg_match('/([0-9]+[.])+[0-9]+/', $row, $date_match);
                if ($date == 1) {
                    $event_date = $date_match[0];
                }
                $event_match = array();
                $match = preg_match('/(?<=>)event.+/i', $row, $event_match);
                if ($match == 1) {
                    $event_raw = $event_match[0];
                    $events[$event_raw] = $event_date;
                }
            }
            foreach ($data['events'] as /* @var $event Event */ &$event) {
                foreach ($events as $raw => $date) {
                    if ($event->getRaw() == $raw) {
                        $event->setDate(date('Y-m-d', strtotime($date)));
                        break;
                    }
                }
            }
        } else {
            foreach ($data['events'] as /* @var $event Event */ &$event) {
                $event->setDate($competition->getStartDate());
            }
        }
        $this->EventModel->insert_events_to_db($data['events']);
        $this->ResultModel->insert_results_to_db($data['results']);

        redirect('competitions');
    }

    public function upload_fina() {
        $config['upload_path'] = sys_get_temp_dir();
        $config['allowed_types'] = 'csv';
        $config['max_size'] = 0;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('fina')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->template('admin/home', $error);
        } else {
            $upload_data = $this->upload->data();
            $full_path = $upload_data['full_path'];
            $this->FinaModel->insert_fina_table_to_db(file($full_path));

            redirect('admin');
        }
    }

    public function upload_rudolph() {
        $config['upload_path'] = sys_get_temp_dir();
        $config['allowed_types'] = 'txt';
        $config['max_size'] = 0;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('rudolph')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->template('admin/home', $error);
        } else {
            $upload_data = $this->upload->data();
            $full_path = $upload_data['full_path'];
            $this->load->model('Rudolph_model', 'RudolphModel');
            $this->RudolphModel->insert_rudolph_table_to_db(file($full_path));

            redirect('admin');
        }
    }

    public function upload_ranks($gender = false) {
        if ($gender !== 'men' && $gender !== 'women') {
            redirect('admin');
        }
        $gender = $gender === 'men' ? 'M' : 'F';

        $config['upload_path'] = sys_get_temp_dir();
        $config['allowed_types'] = 'txt';
        $config['max_size'] = 0;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('ranks')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->template('admin/home', $error);
        } else {
            $upload_data = $this->upload->data();
            $full_path = $upload_data['full_path'];
            $this->load->model('Rank_model', 'RankModel');
            $this->RankModel->insert_rank_table_to_db(file($full_path), $gender);

            redirect('admin');
        }
    }

    public function take_time($str, $start_ms) {
        print_r($str . ((microtime(true) - $start_ms) * 1000) . '<br/>');
    }

    public function add_mdb() {
        $start_ms = microtime(true);
        $events = array();
        $mdb = $this->Utils->mdb_connetion_from_full_path($this->input->post('full_path'));
        $teams = $this->TeamModel->teams_from_mdb($mdb);
        $this->TeamModel->insertNewTeams($teams);

        $athletes = $this->AthleteModel->athletes_from_mdb($mdb);
        $this->AthleteModel->insertNewAthletes($athletes);

        $this->take_time('Athletes', $start_ms);
        $competition_id = $this->CompetitionModel->insertNewCompetition(
                $this->input->post('name'), $this->input->post('city'), $this->input->post('country'), $this->input->post('facility'), $this->input->post('pool'), $this->input->post('start_date'), $this->input->post('end_date')
        );

        $this->take_time('Competition', $start_ms);
        $competition = $this->CompetitionModel->fetch($competition_id);
        $start = strtotime($competition->getStartDate());
        $end = strtotime($competition->getEndDate());
        $days = ($end - $start);
        $data['events'] = $this->EventModel->events_array_from_mdb($mdb, $competition);
        if ($days != 0) {
            $events_found = explode('</li>', $this->input->post('events'));
            foreach ($events_found as $row) {
                $date_match = array();
                $date = preg_match('/([0-9]+[.])+[0-9]+/', $row, $date_match);
                if ($date == 1) {
                    $event_date = $date_match[0];
                }
                $event_match = array();
                $match = preg_match('/(?<=>)event.+/i', $row, $event_match);
                if ($match == 1) {
                    $event_raw = $event_match[0];
                    $events[$event_raw] = $event_date;
                }
            }
            foreach ($data['events'] as /* @var $event Event */ &$event) {
                foreach ($events as $raw => $date) {
                    if (html_entity_decode($event->getRaw()) === html_entity_decode($raw)) {
                        $event->setDate(date('Y-m-d', strtotime($date)));
                        unset($events[$raw]);
                        break;
                    }
                }
            }
        } else {
            foreach ($data['events'] as /* @var $event Event */ &$event) {
                $event->setDate($competition->getStartDate());
            }
        }
        $this->take_time('Events', $start_ms);
        $count = 0;
        $results_all = array();
        foreach ($data['events'] as /* @var $e Event */ $e) {
            $results = $this->ResultModel->results_from_mdb_by_event($mdb, $e);
            $results_all = array_merge($results_all, $results);
        }

        $this->take_time('Results', $start_ms);

        $this->EventModel->insertEventsToDb($data['events']);
        $this->take_time('Events Insert', $start_ms);
        $this->ResultModel->insertResultsRelaysSplits($results_all);
        $this->take_time('Results Insert', $start_ms);
        redirect('competitions');
    }

    public function upload_mdb() {

        $config['upload_path'] = './uploads/databases';
        $config['allowed_types'] = '*';
        $config['max_size'] = 0;
//        $config['file_name'] = $this->generate_file_name($this->user_id);
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('mdb')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->template('admin/home', $error);
        } else {
            $upload_data = $this->upload->data();
            $full_path = $upload_data['full_path'];
            print_r($full_path);
            $data['full_path'] = $full_path;
            $mdb = $this->Utils->mdb_connetion_from_full_path($full_path);

            $competition = $this->CompetitionModel->competition_from_mdb($mdb);
            $data['competition'] = $competition;
            $data['events'] = $this->EventModel->events_array_from_mdb($mdb, $competition);
            $data['country_input'] = $this->Utils->country_dropdown('country', array('EE', 'LV', 'LT', 'FI', 'SE', 'DE', 'FR', 'RU', 'RS', 'NL'));
            $data['count_results'] = $mdb->query("SELECT COUNT(*) as count FROM Results")->row()->count;
            $data['count_events'] = count($data['events']);

            $days = (strtotime($competition->getEndDate()) - strtotime($competition->getStartDate())) / 86400;
            $data['start_date'] = $competition->getStartDate();
            $data['days'] = $days;

            $this->load->template('admin/found_mdb', $data);
        }
    }

    public function upload_json() {

        $competition_id = $this->CompetitionModel->insertNewCompetition(
                $this->input->post('name'), $this->input->post('city'), $this->input->post('country'), $this->input->post('facility'), $this->input->post('pool'), $this->input->post('start_date'), $this->input->post('end_date')
        );
        
       
        $competition = $this->CompetitionModel->fetch($competition_id);

        $teams = json_decode($this->input->post("teams"), true);
        $this->TeamModel->insertNewTeams($teams);
        $athletes = json_decode($this->input->post("athletes"), true);
        $this->AthleteModel->insertNewAthletes($athletes);

        $events = $this->EventModel->populate_events_with_data(json_decode($this->input->post("events"), true), $competition);
        $results = json_decode($this->input->post("results"), true);
        $relays = json_decode($this->input->post("relays"), true);
        $results = $this->ResultModel->populate_results_with_data($results, $relays, $events, $athletes, $teams, $competition);

        $this->EventModel->insertEventsToDb($events);
        $this->ResultModel->insertResultsRelaysSplits($results);
        
        $this->session->set_flashdata('message', 'Võistluse üleslaadimine õnnestus.');
        $this->session->set_flashdata('a_href', site_url("competitions/summary/$competition_id"));
        $this->session->set_flashdata('a_text', 'Ava lisatud võistlus');
        redirect("admin/home");
    }
    
    public function manual_upload_json() {
        $competition = $this->CompetitionModel->fetch($this->input->post("competition_id"));
        $teams = $this->TeamModel->fetchAllLikeJson();
        
        $events = $this->EventModel->populate_events_with_data(json_decode($this->input->post("events"), true), $competition);
        $results = json_decode($this->input->post("results"), true);
        $results = $this->ResultModel->populate_results_with_data($results, array(), $events, array(), $teams, $competition);

        $this->EventModel->insertEventsToDb($events);
        $this->ResultModel->insertResultsRelaysSplits($results);
        
        redirect("admin/competitions/manual/$competition->id");
    }

}